package org.zero.thread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import org.zero.dao.ConfigOperator;
import org.zero.view.ServerWindow;

public class MainThread extends Thread {
	private static MainThread mainThread;

	private ServerWindow serverWindow;
	private boolean runnable;
	private boolean start;

	public static MainThread getInstance() {
		if (mainThread == null) {
			mainThread = new MainThread(ServerWindow.getInstance());
		}
		return mainThread;
	}

	private MainThread(ServerWindow serverWindow) {
		this.serverWindow = serverWindow;
	}

	public boolean isStart() {
		return start;
	}

	public void setStart(boolean start) {
		this.start = start;
	}

	public boolean isRunnable() {
		return runnable;
	}

	public void setRunnable(boolean runnable) {
		this.runnable = runnable;
	}

	@Override
	public void run() {
		int port = ConfigOperator.getPort();
		try (ServerSocket server = new ServerSocket(port)) {
			serverWindow.println("正在监听" + port + "端口，等待来自于客户端的连接......");
			while (runnable) {
				Socket client = server.accept();
				String remoteHost = client.getInetAddress().getHostAddress() + ":" + client.getPort();
				serverWindow.println("\n获取到来自【" + remoteHost + "】的连接");

				serverWindow.println("正在启动【" + remoteHost + "】线程...");
				// 创建并启动线程对象
				new Thread(new ServerThread(client, serverWindow), remoteHost).start();
				serverWindow.println("启动【" + remoteHost + "】线程成功");
			}
		} catch (IOException e) {
			SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(serverWindow, "端口占用\n" + e.getMessage(),
					"错误", JOptionPane.ERROR_MESSAGE));
		}
	}
}
